import 'package:dog_read/components/dotted_separator.dart';
import 'package:dog_read/db/book_db.dart';
import 'package:dog_read/pages/utils/navigator_utils.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:sqflite/sqlite_api.dart';
import 'package:toast/toast.dart';
import 'sites/biquge.dart';
import 'package:dog_read/provider/providers.dart' show ChapterInfosProvider;

class BookDetail extends StatefulWidget {
  final Map arguments;
  BookDetail({this.arguments});
  @override
  _BookDetailState createState() => _BookDetailState(arguments["url"]);
}

class _BookDetailState extends State<BookDetail> {
  final String bookUrl;
  Future _future;
  _BookDetailState(this.bookUrl);

  @override
  void initState() {
    super.initState();
    this._future = BiqugeSpider.getBookDetails(this.bookUrl);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          elevation: 0.0,
          actions: <Widget>[
            Container(
              margin: EdgeInsets.only(right: 12),
              child: IconButton(
                icon: Icon(Icons.home),
                onPressed: () {
                  Navigator.pushNamed(context, "/");
                },
              ),
            )
          ],
        ),
        body: Container(
            height: double.infinity,
            width: double.infinity,
            child: FutureBuilder(
              future: _future,
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                if (snapshot.connectionState != ConnectionState.done) {
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                }
                Map bookInfo = snapshot.data;
                List chapterList = bookInfo["chapterList"];
                int bookId = bookInfo["id"];
                // 设置好章节列表的状态
                Provider.of<ChapterInfosProvider>(context, listen: false)
                  ..setChapterList(chapterList)
                  ..setBookTitle(bookInfo["title"])
                  ..setBookId(bookId);
                return Stack(
                  children: <Widget>[
                    Container(
                        margin: EdgeInsets.all(8.0),
                        child: ListView(
                          shrinkWrap: true,
                          padding: EdgeInsets.all(0.0),
                          children: [
                            BookInfoPart(bookInfo: bookInfo),
                            _chapterEntry(bookInfo, chapterList),
                            _relatedBooks(bookInfo),
                          ],
                        )),
                    BottomPart(
                      bookUrl: this.bookUrl,
                      bookId: bookId,
                    )
                  ],
                );
              },
            )));
  }

  Widget _relatedBooks(bookInfo) {
    List bookList = bookInfo["recommend_books"];
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        SizedBox(
          height: 12.0,
        ),
        Text(
          "看过的读者还看过",
          style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.w700),
        ),
        SizedBox(
          height: 8.0,
        ),
        Wrap(
          alignment:WrapAlignment.center,
          direction: Axis.horizontal,
          spacing: 2.0,
          children: bookList
              .map((e) => ActionChip(
                    pressElevation: 1,
                    shadowColor: Colors.black,
                    backgroundColor: Colors.white,
                    label: Text(
                      "${e['title']}",
                    ),
                    labelStyle: TextStyle(color: Colors.lightBlue),
                    onPressed: () {
                      navToBookDetail(context, title: e['title'], url: e['url']);
                    },
                  ))
              .toList(),
        )
      ],
    );
  }

  Widget _chapterEntry(bookInfo, chapterInfo) {
    return ListTile(
      contentPadding: EdgeInsets.only(left: 0),
      leading: Text(
        "目录",
        style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700),
      ),
      title: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Text(
              "新  ",
              style: TextStyle(
                  color: Colors.redAccent,
                  fontSize: 12,
                  fontWeight: FontWeight.w500),
            ),
          ),
          Expanded(
            flex: 10,
            child: Text(
              "${bookInfo['latest_chapter']}",
              overflow: TextOverflow.ellipsis,
            ),
          )
        ],
      ),
      trailing: Text(
        "${bookInfo['recent_update_time'].split(' ').reversed.toList()[0]}  >",
        style: TextStyle(color: Colors.grey),
      ),
      onTap: () async {
        // 路由到章节列表的详情页面
        Navigator.pushNamed(
          context,
          "/chapter",
        );
      },
    );
  }
}

class BookInfoPart extends StatefulWidget {
  final Map bookInfo;
  BookInfoPart({Key key, this.bookInfo}) : super(key: key);

  @override
  _BookInfoPartState createState() => _BookInfoPartState(bookInfo: bookInfo);
}

class _BookInfoPartState extends State<BookInfoPart> {
  final Map bookInfo;
  _BookInfoPartState({this.bookInfo});
  bool isIntro = false;

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        Card(
          margin: EdgeInsets.only(bottom: 0),
          elevation: 1,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Expanded(
                flex: 4,
                child: Image.network(bookInfo["image_url"]),
              ),
              Expanded(
                flex: 11,
                child: Container(
                    margin: EdgeInsets.only(left: 16.0),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          bookInfo["title"],
                          style: Theme.of(context).textTheme.title,
                        ),
                        Container(
                          margin: EdgeInsets.only(top: 8, bottom: 16),
                          child: Text(
                            bookInfo["author"],
                            style: TextStyle(color: Colors.blue),
                          ),
                        ),
                        Text(
                          "更新状态:" + bookInfo["status"],
                          style: TextStyle(color: Colors.grey),
                        ),
                        SizedBox(
                          height: 4,
                        ),
                        Text(
                          "最新章节:" + bookInfo["latest_chapter"],
                          style: TextStyle(color: Colors.grey),
                        ),
                      ],
                    )),
              ),
            ],
          ),
        ),
        Stack(
          children: <Widget>[
            Container(
              padding: EdgeInsets.only(
                  top: 0, left: 8, right: 8, bottom: isIntro ? 0 : 24),
              margin: EdgeInsets.all(0),
              color: Colors.grey[100],
              child: Text(
                "${bookInfo['description'].replaceAll(r' ', '')}",
                maxLines: isIntro ? 50 : 4,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(color: Colors.grey),
              ),
            ),
            Positioned(
                right: -16,
                bottom: -12,
                child: FlatButton(
                  child: Text(
                    isIntro ? "收起" : "展开",
                    style: TextStyle(color: Colors.lightGreen),
                  ),
                  onPressed: () {
                    setState(() {
                      isIntro = !isIntro;
                    });
                  },
                ))
          ],
        ),
      ],
    );
  }
}

class BottomPart extends StatefulWidget {
  final String bookUrl;
  final int bookId;
  BottomPart({this.bookUrl, this.bookId});

  @override
  _BottomPartState createState() =>
      _BottomPartState(bookUrl: this.bookUrl, bookId: bookId);
}

class _BottomPartState extends State<BottomPart> {
  final String bookUrl;
  final int bookId;
  _BottomPartState({this.bookUrl, this.bookId});

  // Future<bool> _isInShelf(url) async {
  //   Database db = await bookDb;
  //   List book = await db.rawQuery("select * from bookshelf where book_url=?", [url]);
  //   return book.isEmpty ? false : true;
  // }

  // Future _recentReadId(int bookId) async {
  //   Database db = await bookDb;
  //   List ret = await db.rawQuery("select recent_read from book where id=?", [bookId]);
  //   return ret[0]["recent_read"] ?? -1;
  // }

  Future<Map> _getAllInfo(String url, int bookId) async {
    Database db = await bookDb;
    List book =
        await db.rawQuery("select * from bookshelf where book_url=?", [url]);
    List ret =
        await db.rawQuery("select recent_read from book where id=?", [bookId]);
    return {
      "books": book.isEmpty ? false : true,
      "cid": ret[0]["recent_read"] ?? -1
    };
  }

  @override
  Widget build(BuildContext context) {
    return Positioned(
        bottom: 0,
        child: FutureBuilder(
          future: _getAllInfo(bookUrl, bookId),
          builder: (ctx, snapshot) {
            if (snapshot.connectionState != ConnectionState.done) {
              return Center(
                child: CircularProgressIndicator(),
              );
            }
            bool isIn = snapshot.data["books"];
            int cid = snapshot.data["cid"];
            // 只在这里监听index的变化从而更新自己就行了
            Provider.of<ChapterInfosProvider>(context).chapterIndex;
            return Container(
              padding: EdgeInsets.only(top: 8),
              color: Colors.white,
              height: 60,
              width: MediaQuery.of(context).size.width,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Expanded(
                      flex: 1,
                      child: Container(
                        width: 200,
                        child: IconButton(
                          icon: Text(
                            isIn ? "移出书架" : "加入书架",
                            style: TextStyle(
                                fontSize: 16, fontWeight: FontWeight.w400),
                          ),
                          onPressed: () async {
                            Database db = await bookDb;
                            if (isIn) {
                              // 移出书架
                              await db.rawDelete(
                                  "delete from bookshelf where book_url=?",
                                  [bookUrl]);
                              Toast.show("移出成功", context);
                            } else {
                              List bookInfo = await db.rawQuery(
                                  "select id,image_url,title from book where book_url=?",
                                  [bookUrl]);
                              int bookId = bookInfo[0]['id'];
                              String imageUrl = bookInfo[0]['image_url'];
                              String bookTitle = bookInfo[0]['title'];
                              await db.rawInsert(
                                  """insert or replace into bookshelf(book_id, book_title,book_url,image_url,create_time)
                                    values(?,?,?,?,?)""",
                                  [
                                    bookId,
                                    bookTitle,
                                    bookUrl,
                                    imageUrl,
                                    DateTime.now().toString()
                                  ]);
                              Toast.show("添加成功", context);
                            }
                            setState(() {});
                          },
                        ),
                      )),
                  Expanded(
                    flex: 1,
                    child: IconButton(
                      color: Colors.black,
                      icon: Text(cid == -1 ? "开始阅读" : "继续阅读",
                          style: TextStyle(
                              fontSize: 16, fontWeight: FontWeight.w400)),
                      onPressed: () {
                        int index;
                        if (cid == -1) {
                          index = Provider.of<ChapterInfosProvider>(context,
                                      listen: false)
                                  .chapterList
                                  .length -
                              1;
                        } else {
                          index = cid;
                        }
                        Provider.of<ChapterInfosProvider>(context,
                                listen: false)
                            .setChapterIndex(index);
                        Navigator.pushNamed(context, "/chapter/content");
                      },
                    ),
                  )
                ],
              ),
            );
          },
        ));
  }
}
